package com.haitaoit.chengquan.module.login;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.main.MianButtonActivity;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.module.login.Model.LoginInfo;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class LoginActivity extends BaseActivity {
    @ViewInject(R.id.login_phone)
    EditText login_phone;
    @ViewInject(R.id.login_pwd)
    EditText login_pwd;

    /**
     * tag 0直接返回 2 跳向个人中心
     */
    private              String  tag               = "";
    private static final int     LOGIN_NUMBER      = 20;
    private              boolean hasSavePermission = false;
    private String centerfragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ViewUtils.inject(this);
        hasPermission();
        tag = getIntent().getStringExtra("tag");
        centerfragment = getIntent().getStringExtra("centerfragment");

    }

    @OnClick({R.id.left, R.id.login_go, R.id.forget_pwd, R.id.regist,})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.left:
                if (tag.equals("0")) {
                    finish();
                } else {

                    intent.setClass(LoginActivity.this, MianButtonActivity.class);
                    intent.putExtra("index", 0);

                    startActivity(intent);
                    finish();
                }
                break;
            case R.id.login_go:// 登录
                if (login_phone.getText().toString().trim().equals("")) {
                    ToastUtils.showToast("请输入手机号！");
                } else if (login_pwd.getText().toString().trim().equals("")) {
                    ToastUtils.showToast("请输入密码！");
                } else {
                    if (hasNetWork()) {
                        httpGetUserlogin();
                    }
                }
                break;
            case R.id.forget_pwd:// 忘记密码
                intent.setClass(LoginActivity.this, ForgetActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.regist:// 注册
                intent.setClass(LoginActivity.this, RegistSelectActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10:
                login_pwd.setText("");
                break;
        }
    }

    // 登录
    private void httpGetUserlogin() {
        //获取手机唯一标识
        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String equipment = TelephonyMgr.getDeviceId();
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("phone", login_phone.getText().toString()));
        list.add(new NameValuePairSign("password", login_pwd.getText().toString()));
        list.add(new NameValuePairSign("equipment", equipment));
        list.add(new NameValuePairSign("registration_id", ExitApplication.getInstance().getJPushId()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("phone", login_phone.getText().toString());
        params.addQueryStringParameter("password", login_pwd.getText().toString());
        params.addQueryStringParameter("equipment", equipment);
        params.addQueryStringParameter("registration_id", ExitApplication.getInstance().getJPushId());
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(LoginActivity.this, false, Constant.GetUserlogin, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            final LoginInfo loginInfo = gson.fromJson(Response, LoginInfo.class);
                            if (hasSavePermission) {
                                PreferenceUtils.setPrefString("username", login_phone.getText().toString());
                                PreferenceUtils.setPrefString("password", login_pwd.getText().toString());

                                PreferenceUtils.setPrefString("user_id", loginInfo.getUser_id());

                                // 账号的类别
                                PreferenceUtils.setPrefString("account_type", loginInfo.getType());
                                httpGetUserInfo(Constant.Getgr_user_model);
                            } else {
                                ToastUtils.showToast("请设置获取读取内存卡的权限");
                            }
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("网络异常，请检查网络");
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (PreferenceUtils.getPrefString("first", "").equals("2")) {
                Intent intent = new Intent(LoginActivity.this, MianButtonActivity.class);

                startActivity(intent);
                finish();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void httpGetUserInfo(String url) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            UserInfoModel.setUser_info(user_info);
                            PreferenceUtils.setPrefString("address", user_info.getAddress());
                            ToastUtils.showToast("登录成功");
                            finish();

                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }


        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (tag.equals("0")) {
            finish();
        } else {
            Intent intent = new Intent(LoginActivity.this, MianButtonActivity.class);
            intent.putExtra("index", 0);
            startActivity(intent);
            finish();
        }
    }

    private void hasPermission() {
        PermissionGen.with(this)
                .addRequestCode(LOGIN_NUMBER)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .request();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(LoginActivity.this, requestCode, permissions, grantResults);

    }

    @PermissionSuccess(requestCode = LOGIN_NUMBER)
    public void requestPhotoSuccess() {
        login_phone.setText(PreferenceUtils.getPrefString("username", ""));
        login_pwd.setText(PreferenceUtils.getPrefString("password", ""));

        hasSavePermission = true;
    }

    @PermissionFail(requestCode = LOGIN_NUMBER)
    public void requestPhotoFail() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //        Uri uri = Uri.fromParts("package", context.getPackageName());
        //        intent.setData(uri);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);

    }
}
